#!/bin/bash
SCRIPT_PATH="${BASH_SOURCE[0]}"
SCRIPT_DIR="${SCRIPT_PATH%/*}"
if [ "$SCRIPT_DIR" = "$SCRIPT_PATH" ]; then
    SCRIPT_DIR="."
fi
SCRIPT_DIR="$(cd "$SCRIPT_DIR" && pwd)"

OPENOCD_DIR="${SCRIPT_DIR}/../tools/OpenOCD-20240916-0.12.0"
OPENOCD_EXE="$OPENOCD_DIR/bin/openocd.exe"
OPENOCD_IF_CFG="$OPENOCD_DIR/share/openocd/scripts/interface/stlink-v2.cfg"
OPENOCD_TARGET_CFG="$OPENOCD_DIR/share/openocd/scripts/target/stm32f1x.cfg"

ELF_FILE="${1:-rt-thread.elf}"
ELF_FILE_CP="flash_copy.elf"

set -x
cp ${ELF_FILE} ${ELF_FILE_CP}
${OPENOCD_EXE} -f ${OPENOCD_IF_CFG} -f ${OPENOCD_TARGET_CFG}  -c "init; program ${ELF_FILE_CP} verify; reset run; exit"
rm ${ELF_FILE_CP}